<template>
  <div class="sql-query-container">
    <!-- 左侧数据库结构树 -->
    <div class="database-tree">
      <div class="tree-header">
        <h3>数据库结构</h3>
        <button class="refresh-button" @click="refreshDatabases">
          <i class="fas fa-sync"></i>
        </button>
      </div>
      <el-tree
        :data="databaseTree"
        :props="{ label: 'name', children: 'children' }"
        @node-click="handleNodeClick"
        node-key="id"
        :expand-on-click-node="false"
        default-expand-all
      >
        <template #default="{ node, data }">
          <span class="tree-node">
            <i :class="getNodeIcon(data.type)"></i>
            {{ node.label }}
          </span>
        </template>
      </el-tree>
    </div>

    <!-- 右侧查询区域 -->
    <div class="query-area">
      <!-- SQL编辑器 -->
      <div class="editor-container">
        <div class="editor-toolbar">
          <button class="toolbar-button primary" @click="executeQuery">
            <i class="fas fa-play"></i>
            执行查询
          </button>
          <button class="toolbar-button" @click="formatSQL">
            <i class="fas fa-align-left"></i>
            格式化
          </button>
          <button class="toolbar-button" @click="clearEditor">
            <i class="fas fa-eraser"></i>
            清空
          </button>

          <!-- 添加历史记录按钮 -->
          <div class="toolbar-divider"></div>
          <el-dropdown @command="loadHistorySQL" trigger="click">
            <button class="toolbar-button">
              <i class="fas fa-history"></i>
              历史记录
            </button>
            <template #dropdown>
              <el-dropdown-menu class="history-dropdown">
                <div class="history-list">
                  <el-dropdown-item 
                    v-for="(item, index) in sqlHistory"
                    :key="index"
                    :command="item"
                  >
                    <div class="history-item">
                      <span class="history-sql">{{ item.sql.substring(0, 50) }}...</span>
                      <span class="history-time">{{ item.time }}</span>
                    </div>
                  </el-dropdown-item>
                </div>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <!-- 添加快速函数按钮 -->
          <el-dropdown @command="insertFunction" trigger="click">
            <button class="toolbar-button">
              <i class="fas fa-function"></i>
              函数
            </button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="COUNT">COUNT(column)</el-dropdown-item>
                <el-dropdown-item command="SUM">SUM(column)</el-dropdown-item>
                <el-dropdown-item command="AVG">AVG(column)</el-dropdown-item>
                <el-dropdown-item command="MAX">MAX(column)</el-dropdown-item>
                <el-dropdown-item command="MIN">MIN(column)</el-dropdown-item>
                <el-dropdown-item command="DATE">DATE_FORMAT(column, '%Y-%m-%d')</el-dropdown-item>
                <el-dropdown-item command="CONCAT">CONCAT(str1, str2)</el-dropdown-item>
                <el-dropdown-item command="CASE">
                  CASE column 
                    WHEN value THEN result 
                    ELSE default 
                  END
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <!-- 添加AI分析按钮 -->
          <div class="toolbar-divider"></div>
          <button class="toolbar-button ai" @click="analyzeSQL">
            <i class="fas fa-robot"></i>
            AI分析
          </button>

          <!-- 添加AI生成按钮 -->
          <div class="toolbar-divider"></div>
          <button class="toolbar-button ai-generate" @click="showGenerateDialog">
            <i class="fas fa-magic"></i>
            AI生成
          </button>

          <div class="toolbar-divider"></div>
          <el-dropdown @command="handleSaveCommand" trigger="click">
            <button class="toolbar-button save">
              <i class="fas fa-save"></i>
              保存
            </button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="saveNew">保存为新查询</el-dropdown-item>
                <el-dropdown-item 
                  v-if="currentSavedQuery"
                  command="saveUpdate"
                >
                  更新当前查询
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <el-dropdown @command="loadSavedQuery" trigger="click">
            <button class="toolbar-button">
              <i class="fas fa-folder-open"></i>
              我的查询
            </button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item 
                  v-for="query in savedQueries"
                  :key="query.id"
                  :command="query"
                >
                  <div class="saved-query-item">
                    <span class="query-name">{{ query.name }}</span>
                    <span class="query-desc">{{ query.description }}</span>
                    <span class="query-time">{{ query.updateTime }}</span>
                  </div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <div class="editor" ref="sqlEditor"></div>
      </div>

      <!-- 查询结果 -->
      <div class="result-container">
        <div class="result-tabs">
          <div class="tab-header">
            <button 
              v-for="(tab, index) in resultTabs"
              :key="index"
              class="tab-button"
              :class="{ active: currentTab === index }"
              @click="currentTab = index"
            >
              {{ tab.name }}
              <span v-if="tab.type === 'result'" class="row-count">
                ({{ tab.data.length }} 行)
              </span>
            </button>
          </div>

          <!-- 结果表格 -->
          <div v-show="currentTab === 0" class="result-table">
            <el-table
              v-if="resultTabs[0].data.length"
              :data="resultTabs[0].data"
              border
              stripe
              height="calc(100% - 16px)"
              style="width: 100%"
            >
              <el-table-column
                v-for="col in resultTabs[0].columns"
                :key="col"
                :prop="col"
                :label="col"
                show-overflow-tooltip
              />
            </el-table>
            <div v-else class="no-data">
              <i class="fas fa-database"></i>
              <p>执行查询后将在此显示结果</p>
            </div>
          </div>

          <!-- 消息面板 -->
          <div v-show="currentTab === 1" class="message-panel">
            <div 
              v-for="(msg, index) in resultTabs[1].messages"
              :key="index"
              class="message"
              :class="msg.type"
            >
              <i :class="getMessageIcon(msg.type)"></i>
              <span>{{ msg.text }}</span>
              <span class="time">{{ msg.time }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加AI分析弹窗 -->
    <el-dialog
      v-model="aiDialogVisible"
      title="AI SQL分析"
      width="60%"
      :close-on-click-modal="false"
    >
      <div class="ai-analysis">
        <!-- SQL优化建议 -->
        <div class="analysis-section">
          <h4>
            <i class="fas fa-lightbulb"></i>
            优化建议
          </h4>
          <div v-if="aiAnalysis.loading" class="loading">
            <el-spinner />
            <span>AI正在分析...</span>
          </div>
          <div v-else class="suggestions">
            <div v-for="(suggestion, index) in aiAnalysis.suggestions" 
                 :key="index"
                 class="suggestion-item"
            >
              <div class="suggestion-header">
                <span class="suggestion-type">{{ suggestion.type }}</span>
                <el-tag 
                  :type="suggestion.severity === 'high' ? 'danger' : suggestion.severity === 'medium' ? 'warning' : 'info'"
                  size="small"
                >
                  {{ suggestion.severity }}
                </el-tag>
              </div>
              <p class="suggestion-content">{{ suggestion.content }}</p>
              <div v-if="suggestion.optimizedSQL" class="optimized-sql">
                <div class="sql-header">
                  <span>优化后的SQL</span>
                  <button class="copy-button" @click="applySuggestion(suggestion.optimizedSQL)">
                    应用优化
                  </button>
                </div>
                <pre>{{ suggestion.optimizedSQL }}</pre>
              </div>
            </div>
          </div>
        </div>

        <!-- 执行计划分析 -->
        <div class="analysis-section">
          <h4>
            <i class="fas fa-project-diagram"></i>
            执行计划分析
          </h4>
          <div v-if="aiAnalysis.loading" class="loading">
            <el-spinner />
            <span>正在分析执行计划...</span>
          </div>
          <div v-else class="execution-plan">
            <el-table :data="aiAnalysis.executionPlan" border>
              <el-table-column prop="step" label="步骤" width="60" />
              <el-table-column prop="type" label="类型" width="120" />
              <el-table-column prop="description" label="说明" />
              <el-table-column prop="cost" label="成本" width="100" />
            </el-table>
          </div>
        </div>

        <!-- 性能指标 -->
        <div class="analysis-section">
          <h4>
            <i class="fas fa-chart-line"></i>
            性能指标
          </h4>
          <div class="metrics">
            <div class="metric-item">
              <span class="metric-label">预估执行时间</span>
              <span class="metric-value">{{ aiAnalysis.metrics.estimatedTime }}ms</span>
            </div>
            <div class="metric-item">
              <span class="metric-label">预估扫描行数</span>
              <span class="metric-value">{{ aiAnalysis.metrics.estimatedRows }}</span>
            </div>
            <div class="metric-item">
              <span class="metric-label">索引使用率</span>
              <span class="metric-value">{{ aiAnalysis.metrics.indexUsage }}%</span>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 添加AI生成SQL弹窗 -->
    <el-dialog
      v-model="generateDialogVisible"
      title="AI生成SQL"
      width="50%"
      :close-on-click-modal="false"
    >
      <div class="generate-sql">
        <!-- 需求输入 -->
        <div class="requirement-input">
          <h4>
            <i class="fas fa-comment"></i>
            请描述您的查询需求
          </h4>
          <el-input
            v-model="requirement"
            type="textarea"
            :rows="4"
            placeholder="例如：查询最近30天内销售额前10的产品，包含产品名称、销售数量和销售金额"
          />
          <div class="quick-requirements">
            <h5>快速需求</h5>
            <div class="requirement-tags">
              <el-tag
                v-for="(req, index) in quickRequirements"
                :key="index"
                @click="selectRequirement(req)"
                class="clickable"
              >
                {{ req }}
              </el-tag>
            </div>
          </div>
        </div>

        <!-- 相关表信息 -->
        <div class="table-info">
          <h4>
            <i class="fas fa-table"></i>
            相关表信息
          </h4>
          <el-transfer
            v-model="selectedTables"
            :data="availableTables"
            :titles="['可用表', '已选表']"
          />
        </div>

        <!-- 生成结果 -->
        <div v-if="generatedSQL" class="generated-result">
          <div class="result-header">
            <h4>
              <i class="fas fa-code"></i>
              生成的SQL
            </h4>
            <div class="result-actions">
              <el-button size="small" @click="regenerateSQL">
                <i class="fas fa-redo"></i>
                重新生成
              </el-button>
              <el-button type="primary" size="small" @click="useGeneratedSQL">
                <i class="fas fa-check"></i>
                使用此SQL
              </el-button>
            </div>
          </div>
          <div class="sql-preview">
            <pre>{{ generatedSQL }}</pre>
            <div class="sql-explanation">
              <h5>SQL说明</h5>
              <p>{{ sqlExplanation }}</p>
            </div>
          </div>
        </div>

        <!-- 生成中状态 -->
        <div v-if="generating" class="generating-status">
          <el-spinner size="32" />
          <p>AI正在生成SQL，请稍候...</p>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="generateDialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="generateSQL"
            :loading="generating"
            :disabled="!requirement || selectedTables.length === 0"
          >
            生成SQL
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加保存查询弹窗 -->
    <el-dialog
      v-model="saveDialogVisible"
      :title="currentSavedQuery ? '更新查询' : '保存查询'"
      width="500px"
    >
      <div class="save-query-form">
        <el-form 
          ref="saveForm"
          :model="saveForm"
          :rules="saveRules"
          label-width="80px"
        >
          <el-form-item label="名称" prop="name">
            <el-input v-model="saveForm.name" placeholder="请输入查询名称" />
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input
              v-model="saveForm.description"
              type="textarea"
              :rows="3"
              placeholder="请输入查询描述"
            />
          </el-form-item>
          <el-form-item label="标签">
            <el-select
              v-model="saveForm.tags"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择或输入标签"
            >
              <el-option
                v-for="tag in commonTags"
                :key="tag"
                :label="tag"
                :value="tag"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="saveDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitSaveQuery">
            {{ currentSavedQuery ? '更新' : '保存' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import * as monaco from 'monaco-editor'
import { format as sqlFormat } from 'sql-formatter'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

// 编辑器实例
let editor = null
const sqlEditor = ref(null)

// 数据库树结构
const databaseTree = ref([])

// 查询结果标签页
const resultTabs = ref([
  {
    name: '结果',
    type: 'result',
    data: [],
    columns: []
  },
  {
    name: '消息',
    type: 'message',
    messages: []
  }
])

const currentTab = ref(0)

// SQL历史记录
const sqlHistory = ref([])
const MAX_HISTORY = 20

// AI分析相关状态
const aiDialogVisible = ref(false)
const aiAnalysis = ref({
  loading: false,
  suggestions: [],
  executionPlan: [],
  metrics: {
    estimatedTime: 0,
    estimatedRows: 0,
    indexUsage: 0
  }
})

// AI生成SQL相关状态
const generateDialogVisible = ref(false)
const requirement = ref('')
const generating = ref(false)
const generatedSQL = ref('')
const sqlExplanation = ref('')
const selectedTables = ref([])

// 快速需求示例
const quickRequirements = [
  '查询最近7天的日活跃用户数',
  '统计各部门的员工数量和平均工资',
  '查找重复的订单记录',
  '计算每个商品的月度销售趋势'
]

// 可用表列表（从数据库结构中提取）
const availableTables = computed(() => {
  const tables = []
  databaseTree.value.forEach(db => {
    db.children?.forEach(table => {
      tables.push({
        key: table.name,
        label: `${table.name} (${table.children?.length || 0}个字段)`,
        description: table.description || ''
      })
    })
  })
  return tables
})

// 保存查询相关状态
const saveDialogVisible = ref(false)
const saveForm = ref({
  name: '',
  description: '',
  tags: []
})
const saveRules = {
  name: [
    { required: true, message: '请输入查询名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '不能超过200个字符', trigger: 'blur' }
  ]
}
const savedQueries = ref([])
const currentSavedQuery = ref(null)

// 常用标签
const commonTags = [
  '报表查询',
  '数据统计',
  '监控查询',
  '业务分析',
  '日常查询'
]

// 初始化编辑器
const initEditor = () => {
  if (!sqlEditor.value) return
  
  // 注册SQL关键字提示
  monaco.languages.registerCompletionItemProvider('sql', {
    provideCompletionItems: () => {
      const suggestions = [
        {
          label: 'SELECT',
          kind: monaco.languages.CompletionItemKind.Keyword,
          insertText: 'SELECT',
          detail: '查询语句关键字'
        },
        {
          label: 'FROM',
          kind: monaco.languages.CompletionItemKind.Keyword,
          insertText: 'FROM',
          detail: '指定数据表'
        },
        {
          label: 'WHERE',
          kind: monaco.languages.CompletionItemKind.Keyword,
          insertText: 'WHERE',
          detail: '条件过滤'
        },
        {
          label: 'GROUP BY',
          kind: monaco.languages.CompletionItemKind.Keyword,
          insertText: 'GROUP BY',
          detail: '分组'
        },
        {
          label: 'HAVING',
          kind: monaco.languages.CompletionItemKind.Keyword,
          insertText: 'HAVING',
          detail: '分组过滤'
        },
        {
          label: 'ORDER BY',
          kind: monaco.languages.CompletionItemKind.Keyword,
          insertText: 'ORDER BY',
          detail: '排序'
        },
        {
          label: 'LIMIT',
          kind: monaco.languages.CompletionItemKind.Keyword,
          insertText: 'LIMIT',
          detail: '限制结果数量'
        }
      ]

      // 添加表名提示
      databaseTree.value.forEach(db => {
        db.children?.forEach(table => {
          suggestions.push({
            label: table.name,
            kind: monaco.languages.CompletionItemKind.Class,
            insertText: table.name,
            detail: '数据表'
          })
          // 添加字段提示
          table.children?.forEach(column => {
            suggestions.push({
              label: column.name,
              kind: monaco.languages.CompletionItemKind.Field,
              insertText: column.name,
              detail: '字段名'
            })
          })
        })
      })

      return { suggestions }
    }
  })

  editor = monaco.editor.create(sqlEditor.value, {
    value: 'SELECT * FROM users LIMIT 10;',
    language: 'sql',
    theme: 'vs-dark',
    minimap: { enabled: false },
    automaticLayout: true,
    fontSize: 14,
    tabSize: 2,
    scrollBeyondLastLine: false,
    wordWrap: 'on',
    suggestOnTriggerCharacters: true, // 开启触发字符提示
    quickSuggestions: true, // 开启快速提示
    snippetSuggestions: 'inline' // 显示代码片段提示
  })
}

// 获取数据库结构
const refreshDatabases = async () => {
  try {
    const response = await request({
      url: '/api/sql/databases',
      method: 'get'
    })
    databaseTree.value = response.data
    addMessage('success', '数据库结构刷新成功')
  } catch (err) {
    addMessage('error', '获取数据库结构失败: ' + err.message)
  }
}

// 处理节点点击
const handleNodeClick = (data) => {
  if (data.type === 'table') {
    const sql = `SELECT * FROM ${data.name} LIMIT 10;`
    editor.setValue(sql)
  }
}

// 执行查询
const executeQuery = async () => {
  try {
    const sql = editor.getValue()
    if (!sql.trim()) {
      ElMessage.warning('请输入SQL语句')
      return
    }

    // 保存到历史记录
    addToHistory(sql)

    const response = await request({
      url: '/api/sql/execute',
      method: 'post',
      data: { sql }
    })
    
    // 更新结果表格
    resultTabs.value[0].data = response.data.rows || []
    resultTabs.value[0].columns = response.data.columns || []
    
    // 添加成功消息
    addMessage('success', `查询执行成功，返回 ${response.data.rows.length} 条记录`)
    currentTab.value = 0
  } catch (err) {
    addMessage('error', '查询执行失败: ' + err.message)
    currentTab.value = 1
  }
}

// 格式化SQL
const formatSQL = () => {
  try {
    const sql = editor.getValue()
    const formatted = sqlFormat(sql, {
      language: 'sql',
      indent: '  '
    })
    editor.setValue(formatted)
    addMessage('info', 'SQL格式化完成')
  } catch (err) {
    addMessage('error', 'SQL格式化失败: ' + err.message)
  }
}

// 清空编辑器
const clearEditor = () => {
  editor.setValue('')
  addMessage('info', '编辑器已清空')
}

// 添加消息
const addMessage = (type, text) => {
  resultTabs.value[1].messages.unshift({
    type,
    text,
    time: new Date().toLocaleTimeString()
  })
}

// 获取节点图标
const getNodeIcon = (type) => {
  const icons = {
    database: 'fas fa-database',
    table: 'fas fa-table',
    column: 'fas fa-columns'
  }
  return icons[type] || 'fas fa-question'
}

// 获取消息图标
const getMessageIcon = (type) => {
  const icons = {
    success: 'fas fa-check-circle',
    error: 'fas fa-times-circle',
    info: 'fas fa-info-circle'
  }
  return icons[type]
}

// 添加到历史记录
const addToHistory = (sql) => {
  const historyItem = {
    sql,
    time: new Date().toLocaleString()
  }
  sqlHistory.value.unshift(historyItem)
  // 限制历史记录数量
  if (sqlHistory.value.length > MAX_HISTORY) {
    sqlHistory.value.pop()
  }
  // 保存到本地存储
  localStorage.setItem('sqlHistory', JSON.stringify(sqlHistory.value))
}

// 加载历史SQL
const loadHistorySQL = (item) => {
  editor.setValue(item.sql)
  addMessage('info', '已加载历史SQL')
}

// 插入函数
const insertFunction = (func) => {
  const selection = editor.getSelection()
  const range = new monaco.Range(
    selection.startLineNumber,
    selection.startColumn,
    selection.endLineNumber,
    selection.endColumn
  )
  editor.executeEdits('', [{
    range: range,
    text: func,
    forceMoveMarkers: true
  }])
  addMessage('info', '已插入函数')
}

// 分析SQL
const analyzeSQL = async () => {
  const sql = editor.getValue()
  if (!sql.trim()) {
    ElMessage.warning('请输入SQL语句')
    return
  }

  aiDialogVisible.value = true
  aiAnalysis.value.loading = true

  try {
    const response = await request({
      url: '/api/sql/analyze',
      method: 'post',
      data: { sql }
    })

    aiAnalysis.value = {
      ...aiAnalysis.value,
      ...response.data,
      loading: false
    }
  } catch (err) {
    ElMessage.error('AI分析失败: ' + err.message)
    aiAnalysis.value.loading = false
  }
}

// 应用优化建议
const applySuggestion = (optimizedSQL) => {
  editor.setValue(optimizedSQL)
  aiDialogVisible.value = false
  addMessage('success', '已应用优化建议')
}

// 显示生成对话框
const showGenerateDialog = () => {
  generateDialogVisible.value = true
  requirement.value = ''
  generatedSQL.value = ''
  sqlExplanation.value = ''
  selectedTables.value = []
}

// 选择快速需求
const selectRequirement = (req) => {
  requirement.value = req
}

// 生成SQL
const generateSQL = async () => {
  if (!requirement.value || selectedTables.value.length === 0) {
    ElMessage.warning('请输入需求并选择相关表')
    return
  }

  generating.value = true
  try {
    const response = await request({
      url: '/api/sql/generate',
      method: 'post',
      data: {
        requirement: requirement.value,
        tables: selectedTables.value,
        dbStructure: getSelectedTablesStructure()
      }
    })

    generatedSQL.value = response.data.sql
    sqlExplanation.value = response.data.explanation
  } catch (err) {
    ElMessage.error('生成SQL失败: ' + err.message)
  } finally {
    generating.value = false
  }
}

// 重新生成SQL
const regenerateSQL = () => {
  generatedSQL.value = ''
  sqlExplanation.value = ''
  generateSQL()
}

// 使用生成的SQL
const useGeneratedSQL = () => {
  editor.setValue(generatedSQL.value)
  generateDialogVisible.value = false
  addMessage('success', '已应用AI生成的SQL')
}

// 获取选中表的结构信息
const getSelectedTablesStructure = () => {
  const structure = {}
  selectedTables.value.forEach(tableName => {
    databaseTree.value.forEach(db => {
      db.children?.forEach(table => {
        if (table.name === tableName) {
          structure[tableName] = table.children?.map(col => ({
            name: col.name,
            type: col.type,
            description: col.description
          }))
        }
      })
    })
  })
  return structure
}

// 处理保存命令
const handleSaveCommand = (command) => {
  if (command === 'saveNew') {
    saveForm.value = {
      name: '',
      description: '',
      tags: []
    }
    currentSavedQuery.value = null
  } else if (command === 'saveUpdate' && currentSavedQuery.value) {
    saveForm.value = {
      name: currentSavedQuery.value.name,
      description: currentSavedQuery.value.description,
      tags: currentSavedQuery.value.tags || []
    }
  }
  saveDialogVisible.value = true
}

// 提交保存查询
const submitSaveQuery = async () => {
  try {
    await saveForm.value.validate()
    
    const sql = editor.getValue()
    if (!sql.trim()) {
      ElMessage.warning('SQL内容不能为空')
      return
    }

    const data = {
      ...saveForm.value,
      sql,
      id: currentSavedQuery.value?.id
    }

    const response = await request({
      url: currentSavedQuery.value 
        ? '/api/sql/queries/update'
        : '/api/sql/queries/save',
      method: 'post',
      data
    })

    if (currentSavedQuery.value) {
      currentSavedQuery.value = response.data
      ElMessage.success('查询更新成功')
    } else {
      savedQueries.value.unshift(response.data)
      currentSavedQuery.value = response.data
      ElMessage.success('查询保存成功')
    }

    saveDialogVisible.value = false
  } catch (err) {
    ElMessage.error('保存失败: ' + err.message)
  }
}

// 加载保存的查询
const loadSavedQuery = (query) => {
  editor.setValue(query.sql)
  currentSavedQuery.value = query
  addMessage('info', `已加载查询: ${query.name}`)
}

// 获取保存的查询列表
const fetchSavedQueries = async () => {
  try {
    const response = await request({
      url: '/api/sql/queries',
      method: 'get'
    })
    savedQueries.value = response.data
  } catch (err) {
    ElMessage.error('获取保存的查询失败: ' + err.message)
  }
}

onMounted(() => {
  const savedHistory = localStorage.getItem('sqlHistory')
  if (savedHistory) {
    sqlHistory.value = JSON.parse(savedHistory)
  }
  initEditor()
  refreshDatabases()
  fetchSavedQueries()
})

onUnmounted(() => {
  if (editor) {
    editor.dispose()
  }
})
</script>

<style scoped>
.sql-query-container {
  width: 100%;
  height: 100vh;
  display: grid;
  grid-template-columns: 250px 1fr;
  background-color: var(--theme-bg, #f8fafc);
}

.database-tree {
  background-color: var(--theme-container-bg, #ffffff);
  border-right: 1px solid var(--theme-border-color, #e2e8f0);
  overflow-y: auto;
}

.tree-header {
  padding: 12px 16px;
  border-bottom: 1px solid var(--theme-border-color, #e2e8f0);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tree-header h3 {
  margin: 0;
  font-size: 16px;
  color: var(--theme-text-color, #1e293b);
}

.refresh-button {
  padding: 6px;
  background: none;
  border: none;
  cursor: pointer;
  color: var(--theme-text-color, #64748b);
}

.tree-node {
  display: flex;
  align-items: center;
  gap: 8px;
}

.query-area {
  display: grid;
  grid-template-rows: 1fr 1fr;
  gap: 1px;
  background-color: var(--theme-border-color, #e2e8f0);
}

.editor-container {
  background-color: var(--theme-container-bg, #ffffff);
  display: flex;
  flex-direction: column;
}

.editor-toolbar {
  padding: 8px;
  border-bottom: 1px solid var(--theme-border-color, #e2e8f0);
  display: flex;
  gap: 8px;
}

.toolbar-button {
  padding: 8px 12px;
  display: flex;
  align-items: center;
  gap: 6px;
  border: 1px solid var(--theme-border-color, #e2e8f0);
  border-radius: 4px;
  background-color: var(--theme-secondary-bg, #f1f5f9);
  color: var(--theme-text-color, #1e293b);
  cursor: pointer;
  transition: all 0.2s;
}

.toolbar-button.primary {
  background-color: var(--theme-primary-color, #3b82f6);
  color: white;
  border: none;
}

.editor {
  flex: 1;
  overflow: hidden;
  min-height: 200px;
}

.result-container {
  background-color: var(--theme-container-bg, #ffffff);
  display: flex;
  flex-direction: column;
}

.result-tabs {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.tab-header {
  padding: 8px;
  border-bottom: 1px solid var(--theme-border-color, #e2e8f0);
  display: flex;
  gap: 8px;
}

.tab-button {
  padding: 6px 12px;
  border: none;
  background: none;
  color: var(--theme-text-color, #64748b);
  cursor: pointer;
  border-radius: 4px;
}

.tab-button.active {
  background-color: var(--theme-secondary-bg, #f1f5f9);
  color: var(--theme-primary-color, #3b82f6);
}

.row-count {
  margin-left: 4px;
  font-size: 12px;
  opacity: 0.7;
}

.result-table {
  height: 100%;
  padding: 8px;
  overflow: auto;
}

.no-data {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: var(--theme-text-color, #64748b);
}

.no-data i {
  font-size: 48px;
  margin-bottom: 16px;
}

.message-panel {
  padding: 16px;
  overflow-y: auto;
}

.message {
  padding: 8px 12px;
  margin-bottom: 8px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.message.success {
  background-color: #dcfce7;
  color: #166534;
}

.message.error {
  background-color: #fee2e2;
  color: #991b1b;
}

.message.info {
  background-color: #f1f5f9;
  color: #475569;
}

.message .time {
  margin-left: auto;
  font-size: 12px;
  opacity: 0.7;
}

.toolbar-divider {
  width: 1px;
  height: 24px;
  background-color: var(--theme-border-color, #e2e8f0);
  margin: 0 8px;
}

.history-dropdown {
  max-height: 400px !important;
}

.history-list {
  max-height: 400px;
  overflow-y: auto;
}

.history-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
  padding: 8px;
  border-bottom: 1px solid var(--theme-border-color, #e2e8f0);
}

.history-item:last-child {
  border-bottom: none;
}

.history-sql {
  font-family: monospace;
  color: var(--theme-text-color, #1e293b);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.history-time {
  font-size: 12px;
  color: var(--theme-text-color, #64748b);
}

.toolbar-button.ai {
  background-color: #8b5cf6;
  color: white;
  border: none;
}

.ai-analysis {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.analysis-section {
  background-color: var(--theme-container-bg, #ffffff);
  border-radius: 8px;
  padding: 16px;
  border: 1px solid var(--theme-border-color, #e2e8f0);
}

.analysis-section h4 {
  margin: 0 0 16px;
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--theme-text-color, #1e293b);
  font-size: 16px;
}

.loading {
  display: flex;
  align-items: center;
  gap: 12px;
  color: var(--theme-text-color, #64748b);
  padding: 20px 0;
}

.suggestion-item {
  margin-bottom: 16px;
  padding: 12px;
  background-color: var(--theme-secondary-bg, #f8fafc);
  border-radius: 6px;
}

.suggestion-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.suggestion-type {
  font-weight: 500;
  color: var(--theme-text-color, #1e293b);
}

.suggestion-content {
  margin: 8px 0;
  color: var(--theme-text-color, #64748b);
  line-height: 1.5;
}

.optimized-sql {
  margin-top: 12px;
  background-color: var(--theme-bg, #f1f5f9);
  border-radius: 4px;
  overflow: hidden;
}

.sql-header {
  padding: 8px 12px;
  background-color: var(--theme-secondary-bg, #e2e8f0);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.copy-button {
  padding: 4px 8px;
  font-size: 12px;
  background-color: var(--theme-primary-color, #3b82f6);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.optimized-sql pre {
  margin: 0;
  padding: 12px;
  overflow-x: auto;
  font-family: monospace;
}

.metrics {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.metric-item {
  padding: 16px;
  background-color: var(--theme-secondary-bg, #f8fafc);
  border-radius: 6px;
  text-align: center;
}

.metric-label {
  display: block;
  font-size: 14px;
  color: var(--theme-text-color, #64748b);
  margin-bottom: 4px;
}

.metric-value {
  font-size: 24px;
  font-weight: bold;
  color: var(--theme-primary-color, #3b82f6);
}

.toolbar-button.ai-generate {
  background-color: #10b981;
  color: white;
  border: none;
}

.generate-sql {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.requirement-input,
.table-info,
.generated-result {
  background-color: var(--theme-container-bg, #ffffff);
  border-radius: 8px;
  padding: 16px;
  border: 1px solid var(--theme-border-color, #e2e8f0);
}

.requirement-input h4,
.table-info h4,
.generated-result h4 {
  margin: 0 0 16px;
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--theme-text-color, #1e293b);
  font-size: 16px;
}

.quick-requirements {
  margin-top: 16px;
}

.quick-requirements h5 {
  margin: 0 0 8px;
  font-size: 14px;
  color: var(--theme-text-color, #64748b);
}

.requirement-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.clickable {
  cursor: pointer;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.result-actions {
  display: flex;
  gap: 8px;
}

.sql-preview {
  background-color: var(--theme-secondary-bg, #f8fafc);
  border-radius: 6px;
  overflow: hidden;
}

.sql-preview pre {
  margin: 0;
  padding: 16px;
  overflow-x: auto;
  font-family: monospace;
  background-color: var(--theme-bg, #f1f5f9);
}

.sql-explanation {
  padding: 16px;
  border-top: 1px solid var(--theme-border-color, #e2e8f0);
}

.sql-explanation h5 {
  margin: 0 0 8px;
  font-size: 14px;
  color: var(--theme-text-color, #1e293b);
}

.sql-explanation p {
  margin: 0;
  color: var(--theme-text-color, #64748b);
  line-height: 1.5;
}

.generating-status {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  padding: 32px 0;
  color: var(--theme-text-color, #64748b);
}

.toolbar-button.save {
  background-color: #0ea5e9;
  color: white;
  border: none;
}

.saved-query-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
  padding: 4px 0;
}

.query-name {
  font-weight: 500;
  color: var(--theme-text-color, #1e293b);
}

.query-desc {
  font-size: 12px;
  color: var(--theme-text-color, #64748b);
}

.query-time {
  font-size: 12px;
  color: var(--theme-text-color, #94a3b8);
}

/* 暗色主题 */
@media (prefers-color-scheme: dark) {
  .sql-query-container {
    background-color: var(--theme-bg, #0f172a);
  }

  .database-tree,
  .editor-container,
  .result-container {
    background-color: var(--theme-container-bg, #1e293b);
    border-color: var(--theme-border-color, #334155);
  }

  .tree-header h3 {
    color: var(--theme-text-color, #e2e8f0);
  }

  .toolbar-button {
    background-color: var(--theme-secondary-bg, #334155);
    border-color: var(--theme-border-color, #475569);
    color: var(--theme-text-color, #e2e8f0);
  }

  .message.success {
    background-color: #064e3b;
    color: #6ee7b7;
  }

  .message.error {
    background-color: #7f1d1d;
    color: #fca5a5;
  }

  .message.info {
    background-color: #334155;
    color: #cbd5e1;
  }

  .history-item {
    border-color: var(--theme-border-color, #334155);
  }

  .history-sql {
    color: var(--theme-text-color, #e2e8f0);
  }

  .history-time {
    color: var(--theme-text-color, #94a3b8);
  }

  .analysis-section {
    background-color: var(--theme-container-bg, #1e293b);
    border-color: var(--theme-border-color, #334155);
  }

  .suggestion-item {
    background-color: var(--theme-secondary-bg, #334155);
  }

  .optimized-sql {
    background-color: var(--theme-bg, #0f172a);
  }

  .sql-header {
    background-color: var(--theme-secondary-bg, #1e293b);
  }

  .metric-item {
    background-color: var(--theme-secondary-bg, #334155);
  }

  .requirement-input,
  .table-info,
  .generated-result {
    background-color: var(--theme-container-bg, #1e293b);
    border-color: var(--theme-border-color, #334155);
  }

  .sql-preview {
    background-color: var(--theme-secondary-bg, #334155);
  }

  .sql-preview pre {
    background-color: var(--theme-bg, #0f172a);
  }

  .sql-explanation {
    border-color: var(--theme-border-color, #334155);
  }

  .query-name {
    color: var(--theme-text-color, #e2e8f0);
  }

  .query-desc,
  .query-time {
    color: var(--theme-text-color, #94a3b8);
  }
}

/* 自定义滚动条样式 */
.history-list::-webkit-scrollbar {
  width: 6px;
}

.history-list::-webkit-scrollbar-track {
  background: var(--theme-bg, #f1f5f9);
  border-radius: 3px;
}

.history-list::-webkit-scrollbar-thumb {
  background: var(--theme-border-color, #cbd5e1);
  border-radius: 3px;
}

.history-list::-webkit-scrollbar-thumb:hover {
  background: var(--theme-text-color, #94a3b8);
}
</style> 